package com.feixiang.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.feixiang.bean.Role;
import com.feixiang.bean.User;
import com.feixiang.service.PermissionService;
import com.feixiang.service.RoleService;
import com.feixiang.service.UserService;


public class UserRealm  extends AuthorizingRealm {
	 private Logger logger = LoggerFactory.getLogger(UserRealm.class);
	 @Autowired
	 private UserService userService;
	 
	 @Autowired
	 private RoleService roleService;
	 
	 @Autowired
	 private PermissionService permissionService;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
			User user = (User) principals.getPrimaryPrincipal();
	        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	        authorizationInfo.addRoles(roleService.getRoleStrings(user));
	        for(Role role : user.getRoles()){
	        	authorizationInfo.addStringPermissions(permissionService.getPermissionStrings(role));
	        }
	        return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		 User user = userService.findUserByName(token.getUsername());
		 if(user == null){
			 throw new AuthenticationException("unknow user");
		 }
		 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				 user, user.getPassword(),
	                ByteSource.Util.bytes(user.getSalt()), getName());
	     return authenticationInfo;
	}

}
